﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Controllers.RealTime;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("43")]
    public class MileageDetailController : Controller
    {
        //
        // GET: /MileageDetail/
        //里程明细

        private MSPGpsDataContext context = new MSPGpsDataContext();
        private MSPDataContext context1 = new MSPDataContext();

        public ActionResult Index(string startDate, string endDate, string vehicles)
        {
            ViewBag.StartDate = startDate;
            ViewBag.EndDate = endDate;
            ViewBag.Vehicles = vehicles;
            return View();
        }


        public ActionResult Data(string startDate, string endDate, string vehicles, int pageIndex = 1)
        {
            if (Session["SearchData"] != null)
            {
                return PartialView((Session["SearchData"] as IEnumerable<MileageStatistics>).ToPagedList(pageIndex, CommonDictionary.PageSize));
            }

            //得到要查询的车辆id的list
            List<string> vehiclesList = vehicles.Split(';').ToList();

            string endDateStr = Convert.ToDateTime(endDate).AddDays(1).ToString(CommonDictionary.DateStrFormat);

            //得到每天的最早时刻的里程
            var startMileage = from b in context.GpsBasic
                               where vehiclesList.Contains(b.simId) &&
                               string.Compare(b.recordtime, startDate) > 0 &&
                               string.Compare(b.recordtime, endDateStr) < 0
                               group b by new { time = b.recordtime.Substring(0, CommonDictionary.DateStrFormat.Length), b.simId } into bg
                               let first = bg.Min(t => t.recordtime)
                               let simid = bg.Key.simId
                               from b1 in context.GpsBasic
                               where b1.recordtime == first &&
                               b1.simId == simid
                               orderby b1.vehicleId, b1.recordtime
                               select new
                               {
                                   Sim = b1.simId,
                                   VehicleId = b1.vehicleId,
                                   Mileage = b1.mileage==-1?b1.gpsmileage:b1.mileage,
                                   StatisticsTime = b1.recordtime.Substring(0, CommonDictionary.DateStrFormat.Length)
                               };

            //得到每天最后时刻的里程
            var endMileage = from b in context.GpsBasic
                             where vehiclesList.Contains(b.simId) &&
                             string.Compare(b.recordtime, startDate) > 0 &&
                             string.Compare(b.recordtime, endDateStr) < 0
                             group b by new{time=b.recordtime.Substring(0, CommonDictionary.DateStrFormat.Length),b.simId} into bg
                             let last = bg.Max(t => t.recordtime)
                             let simid=bg.Key.simId
                             from b1 in context.GpsBasic
                             where b1.recordtime == last &&
                             b1.simId==simid
                             orderby b1.vehicleId, b1.recordtime
                             select new
                             {
                                 Sim = b1.simId,
                                 VehicleId = b1.vehicleId,
                                 Mileage = b1.mileage == -1 ? b1.gpsmileage : b1.mileage,
                                 StatisticsTime = b1.recordtime.Substring(0, CommonDictionary.DateStrFormat.Length)
                             };

            List<string> paramaters = new List<string>();
            paramaters.Add("0");
            paramaters.Add(CommonDictionary.DateStrFormat.Length.ToString());
            for (int i = 0; i < vehiclesList.Count; i++)
            {
                paramaters.Add(vehiclesList[i].ToVarcharSqlParam());
            }
            paramaters.Add(startDate.ToVarcharSqlParam());
            paramaters.Add(endDateStr.ToVarcharSqlParam());
            paramaters.Add("-1");
            paramaters.Add("0");
            paramaters.Add(CommonDictionary.DateStrFormat.Length.ToString());
            paramaters.Add("0");
            paramaters.Add(CommonDictionary.DateStrFormat.Length.ToString());

            string startMileageJsonStr = RealTimeGet.getReportFromGeoBase(CommonFunctions.GetLoginUser().UserId, CommonFunctions.GetSQL(startMileage, paramaters), startDate, endDate, "0");
            string endMileageJsonStr = RealTimeGet.getReportFromGeoBase(CommonFunctions.GetLoginUser().UserId, CommonFunctions.GetSQL(endMileage, paramaters), startDate, endDate, "0");

            List<MileageStatistics> startMileages = CommonFunctions.JsonStrToObject<List<MileageStatistics>>(startMileageJsonStr);
            List<MileageStatistics> endMileages = CommonFunctions.JsonStrToObject<List<MileageStatistics>>(endMileageJsonStr);

            //最后的里程减去最早的里程
            var mileages = from m1 in endMileages
                           from m2 in startMileages
                           where m1.StatisticsTime == m2.StatisticsTime &&
                           m1.VehicleId==m2.VehicleId
                           orderby m1.StatisticsTime
                           select new MileageStatistics()
                           {
                               Sim = m1.Sim,
                               VehicleId = m1.VehicleId,
                               Mileage = (Convert.ToDouble(m1.Mileage) - Convert.ToDouble(m2.Mileage)).ToString("f3"),
                               StatisticsTime = m1.StatisticsTime
                           };
            List<MileageStatistics> mlist = mileages.ToList<MileageStatistics>();

            //获取车辆的所属单位
            var unit = from v in context1.InfoVehicle
                       from u in context1.InfoUnit
                       where vehiclesList.Contains(v.SIM) &&
                       v.ParentUnitId == u.UNITID
                       select new MileageStatistics()
                       {
                           VehicleId = v.VehicleId,
                           ParentUnitName = u.UNITNAME,
                           Sim = v.SIM,
                       };
            List<MileageStatistics> units=unit.ToList();

            DateTime t1 = Convert.ToDateTime(startDate);
            DateTime t2 = Convert.ToDateTime(endDate);

            //构造每天每车组成的list，因为查出来的数据如果没有某天的数据那么这天的里程要显示为0
            List<MileageStatistics> days = new List<MileageStatistics>();
            for (DateTime t = t1; t <= t2; t = t.AddDays(1))
            {
                for (int i = 0; i < units.Count; i++)
                {
                    days.Add(new MileageStatistics()
                    {
                        VehicleId=units[i].VehicleId,
                        StatisticsTime = t.ToString(CommonDictionary.DateStrFormat),
                        Sim=units[i].Sim,
                        ParentUnitName=units[i].ParentUnitName
                    });
                } 
            }

            var dayMile = from n in days
                          join m in mlist
                          on new { n.StatisticsTime, n.VehicleId } equals new { m.StatisticsTime, m.VehicleId }
                          into nm
                          from nmd in nm.DefaultIfEmpty()
                          orderby n.VehicleId, n.StatisticsTime
                          select new MileageStatistics()
                          {
                              VehicleId = n.VehicleId,
                              Mileage = nmd == null ? "0.000" : nmd.Mileage,
                              StatisticsTime = n.StatisticsTime,
                              ParentUnitName = n.ParentUnitName,
                              Sim = n.Sim
                          };
            Session["SearchData"] = dayMile;
            return PartialView(dayMile.ToPagedList(pageIndex,CommonDictionary.PageSize));
        }

        public ActionResult ExportData()
        {
            CommonController controller = new CommonController();
            Dictionary<string, string> title = new Dictionary<string, string>();
            title.Add("VehicleId", "车牌号");
            title.Add("Sim", "SIM卡号");
            title.Add("ParentUnitName", "所属单位");
            title.Add("StatisticsTime", "统计时间");
            title.Add("Mileage", "里程（公里）");
            string fileName = "里程明细";
            if (Session["SearchData"] != null)
            {
                return controller.ListToExcel<MileageStatistics>((Session["SearchData"] as IEnumerable<MileageStatistics>).ToList(), title, fileName,Server);
            }
            else
            {
                ViewBag.Message = "数据已过期，请重新查询";
                return View("ActionResult");
            }
        }
    }
}
